package com.coffee.mycoffee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coffee.mycoffee.config.exception.CoffeeException;
import com.coffee.mycoffee.mapper.UserMapper;
import com.coffee.mycoffee.pojo.User;
import com.coffee.mycoffee.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 咖啡
 * @since 2020-10-05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Boolean register(User fromUser) {


//        1.校验数据是否为空
        String username = fromUser.getUsername();
        String password = fromUser.getPassword();
        String email = fromUser.getEmail();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(email)) {
            throw new CoffeeException("数据要填写完整", 0);
        }

//      1.根据用户名询用户是否存在
        User getUser = this.getOne(new QueryWrapper<User>().eq("username", username));
//      2.如果用户已经存在，则抛出异常
        if (getUser != null) {
            throw new CoffeeException("用户名已存在", 0);
        }

//      2.生成盐值
        String salt = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
//      5.对密码加盐加密
        String md5HexPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        fromUser
                .setPassword(md5HexPassword)
                .setSalt(salt);
//      6.添加用户
        return this.save(fromUser);
    }
}
